<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>旅行出门天气查询助手 - 移动版</title>
  <link rel="stylesheet" href="./webstack.css">
  <script src="./chart.js"></script>
</head>
<body class="bg-gray-100 p-4">
  <!-- 页面标题 -->
  <h1 class="text-3xl text-center mb-4 mt-2">旅行出门天气查询助手</h1>

  <!-- API Key 输入框和导航 -->
  <div class="space-y-2 mb-4">
    <div class="flex justify-between items-center mb-2">
      <a href="https://dev.qweather.com/docs/api/weather/weather-daily-forecast" target="_blank" class="text-blue-600 hover:text-blue-800 text-sm">本助手使用和风天气API（免费版）</a>
      <a href="index.html" class="bg-blue-500 text-white px-3 py-1 rounded text-sm">电脑版</a>
    </div>
    <input id="appid" type="text" placeholder="输入 API Key" class="border p-2 w-full rounded">
  </div>

  <!-- 城市输入和按钮 -->
  <div class="space-y-2 mb-4">
    <input id="cityName" type="text" placeholder="输入城市名，最多添加7个" class="border p-2 w-full rounded">
    <button id="addCity" class="bg-blue-500 text-white p-2 w-full rounded">添加观察城市</button>
    <button id="fetchWeather" class="bg-green-600 text-white p-2 w-full rounded">一键查询天气</button>
  </div>

  <!-- 城市列表表格 -->
  <div class="bg-white p-2 rounded shadow mb-4 overflow-x-auto">
    <table id="cityTable" class="w-full">
      <thead>
        <tr>
          <th class="border px-2 py-1">城市名称</th>
          <th class="border px-2 py-1">操作</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
  </div>

  <!-- 最高气温折线图容器 -->
  <div class="bg-white p-2 rounded shadow mb-4">
    <canvas id="maxTempChart"></canvas>
  </div>

  <!-- 最低气温折线图容器 -->
  <div class="bg-white p-2 rounded shadow mb-4">
    <canvas id="minTempChart"></canvas>
  </div>

  <!-- 天气结果表格 -->
  <div class="bg-white p-2 rounded shadow overflow-x-auto">
    <table class="w-full">
      <thead>
        <tr>
          <th class="border px-2 py-1 text-sm">城市</th>
          <th class="border px-2 py-1 text-sm">日期</th>
          <th class="border px-2 py-1 text-sm">天气</th>
          <th class="border px-2 py-1 text-sm">湿度</th>
          <th class="border px-2 py-1 text-sm">最高温</th>
          <th class="border px-2 py-1 text-sm">最低温</th>
          <th class="border px-2 py-1 text-sm">风速</th>
        </tr>
      </thead>
      <tbody id="weatherTable"></tbody>
    </table>
  </div>

  <script>
    const MAX_CITIES = 7; // 最大城市数量限制
    let cities = JSON.parse(sessionStorage.getItem('cities') || '[]');
    let maxTempChart = null;
    let minTempChart = null;

    // 渲染城市表格
    function renderCityTable() {
      const tbody = document.getElementById('cityTable').querySelector('tbody');
      tbody.innerHTML = '';
      
      cities.forEach((city, index) => {
        const row = document.createElement('tr');
        row.innerHTML = `
          <td class="border px-2 py-1 text-center text-sm">${city}</td>
          <td class="border px-2 py-1 text-center">
            <button onclick="removeCity(${index})" class="bg-red-500 text-white px-2 py-1 rounded text-sm">删除</button>
          </td>
        `;
        tbody.appendChild(row);
      });

      // 更新添加按钮状态
      const addButton = document.getElementById('addCity');
      const cityInput = document.getElementById('cityName');
      if (cities.length >= MAX_CITIES) {
        addButton.disabled = true;
        cityInput.disabled = true;
        addButton.classList.add('opacity-50', 'cursor-not-allowed');
        cityInput.classList.add('opacity-50', 'cursor-not-allowed');
      } else {
        addButton.disabled = false;
        cityInput.disabled = false;
        addButton.classList.remove('opacity-50', 'cursor-not-allowed');
        cityInput.classList.remove('opacity-50', 'cursor-not-allowed');
      }
    }

    // 添加城市函数
    function addCity() {
      const cityName = document.getElementById('cityName').value.trim();

      if (cities.length >= MAX_CITIES) {
        alert(`最多只能添加${MAX_CITIES}个城市`);
        return;
      }

      if (!cityName) {
        alert('请输入城市名称');
        return;
      }

      if (cities.includes(cityName)) {
        alert('该城市已经添加过了');
        return;
      }

      cities.push(cityName);
      sessionStorage.setItem('cities', JSON.stringify(cities));
      document.getElementById('cityName').value = '';
      renderCityTable();
    }

    // 移除城市函数
    function removeCity(index) {
      cities.splice(index, 1);
      sessionStorage.setItem('cities', JSON.stringify(cities));
      renderCityTable();
    }

    // 获取天气数据函数
    async function getWeatherData(cityName, appid) {
      try {
        // 先获取城市ID
        const cityResponse = await fetch(`https://geoapi.qweather.com/v2/city/lookup?key=${appid}&location=${cityName}`);
        const cityData = await cityResponse.json();
        
        if (cityData.code !== "200" || !cityData.location || cityData.location.length === 0) {
          throw new Error('获取城市ID失败');
        }

        // 使用第一个城市的ID获取天气数据
        const cityId = cityData.location[0].id;
        const weatherResponse = await fetch(`https://devapi.qweather.com/v7/weather/7d?key=${appid}&location=${cityId}`);
        const weatherData = await weatherResponse.json();

        if (weatherData.code !== "200") {
          throw new Error('获取天气数据失败');
        }

        return weatherData;
      } catch (error) {
        console.error('获取天气数据失败:', error);
        throw error;
      }
    }

    // 绑定添加按钮事件
    document.getElementById('addCity').addEventListener('click', addCity);

    // 绑定输入框回车事件
    document.getElementById('cityName').addEventListener('keypress', function(e) {
      if (e.key === 'Enter') {
        addCity();
      }
    });

    // 获取天气函数
    document.getElementById('fetchWeather').addEventListener('click', async function () {
      const appid = document.getElementById('appid').value.trim();

      if (!appid) {
        alert('请填写 API Key');
        return;
      }

      // 保存到 sessionStorage
      sessionStorage.setItem('appid', appid);
      sessionStorage.setItem('storeTime', new Date().getTime());

      const weatherTable = document.getElementById('weatherTable');
      weatherTable.innerHTML = '';

      const weatherData = await Promise.all(cities.map(async (city) => {
        try {
          const data = await getWeatherData(city, appid);
          
          const result = {
            city: city,
            forecast: data.daily.map(day => ({
              date: day.fxDate,
              weather: day.textDay,
              humidity: day.humidity,
              temp_max: day.tempMax,
              temp_min: day.tempMin,
              win_speed: `${day.windDirDay}${day.windScaleDay}级`
            }))
          };
          
          return result;
        } catch (error) {
          console.error('获取天气数据失败:', error, '城市:', city);
          return null;
        }
      }));

      // 过滤掉null值并按最高温度排序
      const validWeatherData = weatherData.filter(data => data !== null);

      // 只有在有有效数据时才继续处理
      if (validWeatherData.length > 0) {
        validWeatherData.sort((a, b) => parseInt(a.forecast[0].temp_max) - parseInt(b.forecast[0].temp_max));

        // 渲染天气表格
        validWeatherData.forEach((cityData) => {
          cityData.forecast.forEach((data) => {
            const row = document.createElement('tr');
            row.innerHTML = `
              <td class="border px-2 py-1 text-center text-sm">${cityData.city}</td>
              <td class="border px-2 py-1 text-center text-sm">${data.date}</td>
              <td class="border px-2 py-1 text-center text-sm">${data.weather}</td>
              <td class="border px-2 py-1 text-center text-sm">${data.humidity}%</td>
              <td class="border px-2 py-1 text-center text-sm">${data.temp_max}°C</td>
              <td class="border px-2 py-1 text-center text-sm">${data.temp_min}°C</td>
              <td class="border px-2 py-1 text-center text-sm">${data.win_speed}</td>
            `;
            weatherTable.appendChild(row);
          });
        });

        // 绘制折线图
        drawWeatherCharts(validWeatherData);
      } else {
        weatherTable.innerHTML = '<tr><td colspan="7" class="border px-2 py-1 text-center text-sm">暂无有效天气数据</td></tr>';
      }
    });

    // 绘制折线图函数
    function drawWeatherCharts(weatherData) {
      const maxTempCtx = document.getElementById('maxTempChart').getContext('2d');
      const minTempCtx = document.getElementById('minTempChart').getContext('2d');

      // 清除之前的图表实例
      if (maxTempChart) maxTempChart.destroy();
      if (minTempChart) minTempChart.destroy();

      const colors = [
        'rgba(255, 99, 132, 0.6)',
        'rgba(54, 162, 235, 0.6)',
        'rgba(255, 206, 86, 0.6)',
        'rgba(75, 192, 192, 0.6)',
        'rgba(153, 102, 255, 0.6)',
        'rgba(255, 159, 64, 0.6)',
        'rgba(199, 199, 199, 0.6)'
      ];

      const dates = weatherData[0].forecast.map(day => day.date);

      const chartOptions = {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            position: 'bottom',
            labels: {
              boxWidth: 12,
              font: {
                size: 10
              }
            }
          }
        },
        scales: {
          x: {
            ticks: {
              font: {
                size: 10
              }
            }
          },
          y: {
            ticks: {
              font: {
                size: 10
              }
            }
          }
        }
      };

      maxTempChart = new Chart(maxTempCtx, {
        type: 'line',
        data: {
          labels: dates,
          datasets: weatherData.map((cityData, index) => ({
            label: cityData.city,
            data: cityData.forecast.map(day => day.temp_max),
            borderColor: colors[index % colors.length],
            fill: false
          }))
        },
        options: {
          ...chartOptions,
          plugins: {
            ...chartOptions.plugins,
            title: {
              display: true,
              text: '最高气温 (°C)',
              font: {
                size: 14
              }
            }
          }
        }
      });

      minTempChart = new Chart(minTempCtx, {
        type: 'line',
        data: {
          labels: dates,
          datasets: weatherData.map((cityData, index) => ({
            label: cityData.city,
            data: cityData.forecast.map(day => day.temp_min),
            borderColor: colors[index % colors.length],
            fill: false
          }))
        },
        options: {
          ...chartOptions,
          plugins: {
            ...chartOptions.plugins,
            title: {
              display: true,
              text: '最低气温 (°C)',
              font: {
                size: 14
              }
            }
          }
        }
      });
    }

    // 初始化页面
    renderCityTable();

    // 初始化 sessionStorage 数据
    const storedAppId = sessionStorage.getItem('appid');
    const storedTime = sessionStorage.getItem('storeTime');
    const currentTime = new Date().getTime();

    if (storedAppId && storedTime && (currentTime - storedTime) < 86400000) {
      document.getElementById('appid').value = storedAppId;
    } else {
      sessionStorage.removeItem('appid');
      sessionStorage.removeItem('storeTime');
    }
  </script>
</body>
</html>